package com.econage.eccm.test.base.webdatasource.web;

import com.google.common.util.concurrent.RateLimiter;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

public class DbTransaction {

    private static volatile AppDataSourceContext appDataSourceContext;
    private static RateLimiter rateLimiter = RateLimiter.create(1,30, TimeUnit.SECONDS);
    static void checkAppDataSource(){
        if(appDataSourceContext==null){
            if(!rateLimiter.tryAcquire()){
                throw new IllegalStateException("操作过于频繁，请30秒后重试!");
            }
            synchronized (AppDataSourceFilter.class){
                try {
                    appDataSourceContext = new AppDataSourceContext();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static AppDataSourceContext getAppDataSourceContext(){
        checkAppDataSource();
        return appDataSourceContext;
    }

    public static Connection fetchConnection(){
        try {
            return getAppDataSourceContext().fetchConnection();
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }
    }

    static void register4Access(){
        getAppDataSourceContext().register4Access();
    }

    static void closeForce(){
        try {
            getAppDataSourceContext().closeForce();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void commit() throws SQLException {
        getAppDataSourceContext().fetchConnection().commit();
    }
    public static void rollback() throws SQLException {
        getAppDataSourceContext().fetchConnection().rollback();
    }

    public static String getDbUrl(){
        return getAppDataSourceContext().getDbUrl();
    }
}
